package com.iot.task;

import com.iot.beidou.SerialPortUtil;
import com.iot.beidou.dto.SerialPortMsg;
import gnu.io.SerialPort;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component("bedouinCommandQueryTask")
public class BedouinCommandQueryTask {
    private static final Logger logger = LoggerFactory.getLogger(BedouinCommandQueryTask.class);
    private static String strVerification(int commandTestLen, char[] commandTestChar, String commandPub){
        String commandAll;
        String checkResult= "";
        int check = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0;i<commandTestLen;i++){
            char[] str;
            char[] str_= new char[3];
            str = Integer.toHexString((int)commandTestChar[i]).toCharArray();
            str_[0]=str[0];
            str_[1]=0;
            sb.append(str_);
            str_[0]=str[1];
            str_[1]=0;
            sb.append(str_);
            checkResult = sb.toString();
        }
        commandAll = commandPub+checkResult;
        int len = commandAll.length();
        for (int i=0;i<len;i++){
            check = check^commandAll.toCharArray()[i];
        }
        String checkString = String.format("%02X",check);
        return checkString;
    }
    public void sendQueriesToDevice(){
        String commandCommonPart = "CCTXA,404721,1,2,A4";
        String commandText;
        String checkCode;
        String checkSend;
        byte[] commandSendByte;
        String commandTextPre = "2A30303";
        String commandTextSuf = "2A560D0A";
        try {
            //获取串号
            SerialPort serialPort = SerialPortMsg.serialPort;
            SerialPortUtil serialPortUtil = SerialPortUtil.getSerialPortUtil();
            logger.info("正在使用端口号：{}",serialPort);
            if (serialPort==null){
                logger.info("卫星未连接,端口号查询结果：{null}");
            }else {
                for (int i=0;i<=7;i++){
                    Thread.sleep(61000);
                    commandText = commandTextPre+(i+1)+commandTextSuf;
                    logger.info("发送的字符串拼接结果：{}",commandText);
                    char[] commandTextChar = commandText.toCharArray();
                    /*
                      字符串校验
                     */
                    checkCode= strVerification(commandText.length(),commandTextChar,commandCommonPart);
                    checkSend = "$"+commandCommonPart+commandText+"*"+ checkCode+"\r\n";
                    commandSendByte = checkSend.getBytes();
                    serialPortUtil.sendToPort(serialPort,commandSendByte);
                }
            }
        }catch (Exception ignored){
             ignored.getMessage();
        }
    }


}
